import router from './router'
import store from './store'

const whiteList = ['/login', 'error']
router.beforeEach((to, from, next) => {
	    if(store.getters.store_token) {
			if(to.path === '/login') {
	            next({path: '/'});
	        } else {
	            if(store.getters.store_phone === ''){
	                store.dispatch('StoreGetInfo').then(res => {
	                    const permissions = res.permissions;
	                    store.dispatch('StoreGenerateRoutes', {permissions}).then(() => {
							router.addRoutes(store.getters.store_add_routers);
	                        next(to.path);
	                    });
	                }).catch((err) => {
					  store.dispatch('logout').then(() => {
						Message.error(err || '验证失败, 请重新登陆')
						next({ path: '/' })
					  })
					})
	            } else {
	                if(hasPermission(store.getters.store_permissions, to.name)) {
	                    next();
	                } else {
	                    next({
	                        path: '/403',
	                        query: {
	                            noGoBack:true
	                        }
	                    });
	                }
	            }
	        }
	    } else {
	        if(whiteList.indexOf(to.path) !== -1) {
	            next();
	        } else {
	            next('/login');
	            
	        }
	    }
})
function hasPermission(permissions, name) {
    if (name) {
        for (let permission of permissions) {
            if (permission.name === name) return true;
            if (permission.submenus) {
				for (let submenu of permission.submenus) {
                    if (submenu.name === name) return true;
                }
            }
        }
        return false;
    } else {
        return true
    }
}
